﻿

using System;
using System.Collections.Generic;
using mds.BaseFrameModel;
using System.Data.SqlClient;
using System.Data;

namespace mds.DataAccessService
{
    public class SqlServerDatabase<T>
    {
        public int ExecuteNonQuery(string connectionString, string sql, CommandType cmdType, List<SqlDataParmeter> pamarmeters, bool isMultiStore = false)
        {
            if(isMultiStore)
            connectionString = Util.ParseCon(connectionString, pamarmeters);
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(sql, con);
            if (pamarmeters != null)
            {
                pamarmeters.ForEach(a =>
                {
                    cmd.Parameters.Add(new SqlParameter(a.ParamterName, a.ParamterVal));
                });
            }
            cmd.CommandType = cmdType;
            con.Open();
            int result= cmd.ExecuteNonQuery();
            con.Close();
            return result;
        }

       
        public delegate T initData<T>(SqlDataReader dataReader);

        protected static T GetDataByReader<T>(string connectionName, List<SqlParameter> parameters, string cmdText, CommandType cmdType, initData<T> dataAction)
        {
            SqlConnection con = new SqlConnection(DataConnectionFactory.GetConnectionString(connectionName));
            SqlCommand cmd = new SqlCommand(cmdText, con);
            if (parameters != null)
                cmd.Parameters.AddRange(parameters.ToArray());
            cmd.CommandType = cmdType;
            con.Open();
            var dataReader = cmd.ExecuteReader();
            T data = dataAction(dataReader);
            dataReader.Close();
            con.Close();
            return data;
        }
        public delegate void initList<T>(SqlDataReader dataReader, List<T> result);

        protected static List<T> GetListByReader<T>(string connectionName, List<SqlParameter> parameters, string cmdText, CommandType cmdType, initList<T> dataAction)
        {
            SqlConnection con = new SqlConnection(DataConnectionFactory.GetConnectionString(connectionName));
            SqlCommand cmd = new SqlCommand(cmdText, con);
            if (parameters != null)
                cmd.Parameters.AddRange(parameters.ToArray());
            cmd.CommandType = cmdType;
            con.Open();
            var dataReader = cmd.ExecuteReader();
            List<T> data = new List<T>();
            dataAction(dataReader, data);
            dataReader.Close();
            con.Close();
            return data;
        }
    }
}
